import { useMemoizedFn } from 'ahooks';
import { useState } from 'react';
import { useContextSelector } from 'use-context-selector';

import AppQA from '@/pages/app-qa';
import { streamFetch } from '@/pages/app-qa/components/chat/tools/fetch';
import { StartChatFnProps } from '@/pages/chat/tools/constants';
import { AppChatConfigType, AppTypeEnum } from '@/types/app/type';
import { ChatSiteItemType } from '@/types/chat/type';
import { StoreEdgeItemType } from '@/types/workflow/edge';
import { StoreNodeItemType } from '@/types/workflow/node';
import { getMaxHistoryLimitFromNodes } from '@/types/workflow/runtime/utils';

import { AppContext } from '../../context';

export const useChatTest = ({
  nodes,
  edges,
  chatConfig,
  initChatId,
}: {
  nodes: StoreNodeItemType[];
  edges: StoreEdgeItemType[];
  chatConfig: AppChatConfigType;
  initChatId: string;
}) => {
  const { appDetail } = useContextSelector(AppContext, (v) => v);
  const [chatRecords] = useState<ChatSiteItemType[]>([]);

  const startChat = useMemoizedFn(
    async ({ messages, controller, generatingMessage, variables }: StartChatFnProps) => {
      /* get histories */
      const historyMaxLen = getMaxHistoryLimitFromNodes(nodes);
      console.log('messages', messages, historyMaxLen);
      // 流请求，获取数据
      const { responseText, responseData } = await streamFetch({
        url: '/api/openapi/v1/chat/chatTest',
        data: {
          // Send histories and user messages
          messages: messages.slice(-historyMaxLen - 2),
          nodes,
          edges,
          variables,
          appId: appDetail.id,
          appName: `调试-${appDetail.name}`,
          chatConfig,
        },
        onMessage: generatingMessage,
        abortCtrl: controller,
      });

      return { responseText, responseData };
    },
  );

  // TODO
  const CustomChatContainer = useMemoizedFn(() =>
    appDetail.type === AppTypeEnum.plugin ? (
      <div>
        {/* <PluginRunBox
          pluginInputs={pluginInputs}
          variablesForm={variablesForm}
          histories={chatRecords}
          setHistories={setChatRecords}
          appId={appDetail._id}
          chatConfig={appDetail.chatConfig}
          tab={pluginRunTab}
          setTab={setPluginRunTab}
          onNewChat={() => {
            clearChatRecords();
            setChatRecords([]);
          }}
          onStartChat={startChat}
        /> */}
        plugin
      </div>
    ) : (
      <AppQA onStartChat={startChat} workflowDebug />
    ),
  );

  return {
    ChatContainer: CustomChatContainer,
    chatRecords,
  };
};

export default useChatTest;
